<template>
  <div style="width: fit-content">
    <div class="container" ref="containerRef">
      <div class="markdown-body" :id="attrs.uuid" :class="{ 'markdown-body-generate': isloading }" v-html="messageText"></div>
    </div>
    <div v-if="!isQuention && !isloading" style="display: flex; justify-content: flex-end; margin-top: 10px">
      <el-icon @click="copyToClip(text)"><CopyDocument style="cursor: pointer" /></el-icon>
    </div>
  </div>
</template>

<script setup>
import MarkdownIt from 'markdown-it'
import mdKatex from '@traptitech/markdown-it-katex'
import mila from 'markdown-it-link-attributes'
import hljs from 'highlight.js'
import { computed, onMounted, onUpdated, ref, useAttrs, watch } from 'vue'
const attrs = useAttrs()

const mdi = new MarkdownIt({
  html: false,
  linkify: true,
  highlight(code, language) {
    const validLang = !!(language && hljs.getLanguage(language))
    if (validLang) {
      const lang = language ?? ''
      return highlightBlock(hljs.highlight(code, { language: lang }).value, lang)
    }
    return highlightBlock(hljs.highlightAuto(code).value, '')
  },
})

function highlightBlock(str, lang) {
  return `<pre class="code-block-wrapper"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">复制代码</span></div><code class="hljs code-block-body ${lang}">${str}</code></pre>`
}
const props = defineProps({
  text: {
    type: String,
    default: '',
  },
  isloading: {
    type: Boolean,
    default: false,
  },
  isQuention: {
    type: Boolean,
    default: false,
  },
})
onMounted(() => {
  addCopyEvent()
})

onUpdated(() => {
  addCopyEvent()
})

const messageText = computed(() => {
  return mdi.render(props.text)
})

const containerRef = ref()
function addCopyEvent() {
  const copyBtn = containerRef.value.querySelector('.code-block-header__copy')
  copyBtn?.addEventListener('click', () => {
    const code = copyBtn?.parentElement?.nextElementSibling?.textContent
    if (code) {
      copyToClip(code).then(() => {
        copyBtn.textContent = '复制成功'
        setTimeout(() => {
          copyBtn.textContent = '复制代码'
        }, 1000)
      })
    }
  })
}
function copyToClip(text) {
  return new Promise((resolve, reject) => {
    try {
      const input = document.createElement('textarea')
      input.value = text
      input.setAttribute('readonly', 'readonly')
      document.body.appendChild(input)
      input.select()
      if (document.execCommand('copy')) {
        document.execCommand('copy')
        document.body.removeChild(input)
        resolve(text)
      }
    } catch (error) {
      reject(error)
    }
  })
}
</script>

<style lang="scss">
@import './style.scss';
.container {
  padding: 5px 10px;
  background-color: #f0f2fa;
  width: fit-content;
  border-radius: 20px;
}
.hljs {
  background: transparent;
}
.code-block-wrapper {
  padding: 20px;
}
</style>
